<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/14
 * Time: 8:48
 * Created by Created by Panxsoft.
 */

namespace App\Services\Repositories;

use App\Models\Categories\Category;
use App\Models\Categories\CategoryDescription;
use App\Models\Categories\CategoryToStore;
use App\Models\Store;
use App\Services\MobileApp\AppEnv;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Query\JoinClause;

class CategoryRepository
{

    /**
     * @param int $category_id
     * @param string $filter_type
     *
     * @return \Illuminate\Support\Collection
     */
    public function getCategories(int $category_id, string $filter_type)
    {
        $store_id = AppEnv::storeId();
        $cateModel = new Category;
        $cateDescModel = new CategoryDescription;
        /** @var DatabaseManager $db */
        $db = app('db');
        $prefix = $db->getTablePrefix();
        // PM 要求 App 和 OC 网页显示顺序一样，查看网页逻辑是先 sort_order 再 join 对应描述表的 name 升序的
        $lc_desc_name = \DB::raw("LCASE({$prefix}{$cateDescModel->qualifyColumn('name')})");

        $categories = $cateModel
            ->select(
                $cateModel->qualifyColumn('*'),
                $cateDescModel->qualifyColumn('name as category_description_name')
            )
            ->where('status', Category::CATEGORY_STATUS_ON)
            ->whereHas('categoryToStores', function(Builder $query) use($store_id){
                return $query->where('store_id', $store_id);
            })
            ->leftJoin($cateDescModel->getTable(), function (JoinClause $join) use ($cateModel, $cateDescModel) {
                $join->on($cateModel->getQualifiedKeyName(), $cateDescModel->qualifyColumn('category_id'))
                    ->where($cateDescModel->qualifyColumn('language_id'), AppEnv::languageId());
            })
            ->oldest('sort_order')
            ->oldest($lc_desc_name)
            ->where('parent_id', $category_id)
            ->get();

        return $this->formatCategories($categories, $filter_type);
    }

    /**
     * @param Collection $categories
     * @param string $filter_type
     *
     * @return \Illuminate\Support\Collection
     */
    public function formatCategories(Collection $categories, string $filter_type)
    {
        return $categories->map(function (Category $category) use ($filter_type) {
            return [
                'category_id'  => $category->category_id,
                'image'        => $category->image,
                'parent_id'    => $category->parent_id,
                'name'         => $category->category_description_name,
                'sort_order'   => $category->sort_order,
                'origin_image' => $category->origin_image,
                'children'     => $filter_type === Category::FILTER_TYPE_ALL
                    ? $this->getCategories($category->getKey(), $filter_type)
                    : []
            ];
        });
    }
}

